import { createSlice } from '@reduxjs/toolkit';
import Mock from 'mockjs';
import posts from '../mock/posts'
import AsyncStorage from '@react-native-async-storage/async-storage';
const postSlice = createSlice({
    name: 'post',
    initialState: {
        posts: posts
    },
    reducers: {
        // 初始化帖子
        setPosts: (state, action) => {
            state.posts = action.payload
        },
        // 添加一条动态
        addPost: (state, action) => {
            const post = Mock.mock({
                id: '@guid',
                userId: action.payload.userId,
                name: '@cname', // 随机生成昵称
                avatar: '@image("100x100", "@color", "Avatar")', // 随机生成头像
                gender: '@pick(["男", "女"])', // 随机生成性别
                focus: [], // 关注
                fans: [], // 粉丝
                content: action.payload.content, // 用户输入内容
                media: action.payload.media, // 用户上传的媒体文件
                location: action.payload.location, // 用户位置
                country: action.payload.country, // 用户所在国家/地区
                createTime: action.payload.createTime, // 随机生成时间
                goods: action.payload.goods, //点赞列表，初始为[]
                comments: action.payload.comments, // 评论列表，初始为[]
            });
            state.posts.unshift(post);
            savePostsToStorage(state.posts);
        },
        // 添加评论
        addComment: (state, action) => {
            const { postid, comment } = action.payload;
            const postIndex = state.posts.findIndex((p) => p.id === postid);

            if (postIndex !== -1) {
                // 创建新的帖子对象，确保状态不可变性
                const updatedPost = {
                    ...state.posts[postIndex],
                    comments: [comment, ...state.posts[postIndex].comments], // 添加新评论
                };
                // 更新 Redux 状态
                state.posts[postIndex] = updatedPost;
                // 持久化存储
                savePostsToStorage(state.posts);
            }
        },
        // 点赞/取消赞
        addGood: (state, action) => {
            const { postid, good } = action.payload;
            const postIndex = state.posts.findIndex((p) => p.id === postid);
            if (postIndex !== -1) {
                const post = state.posts[postIndex];
                const isAlreadyLiked = post.goods.some((item) => item.id === good.id);
                // 根据是否已点赞，更新 goods
                const updatedGoods = isAlreadyLiked
                    ? post.goods.filter((item) => item.id !== good.id) // 取消点赞
                    : [good, ...post.goods]; // 点赞

                // 创建新的帖子对象，保持不可变性
                const updatedPost = {
                    ...post,
                    goods: updatedGoods,
                };
                // 更新 Redux 状态
                state.posts[postIndex] = updatedPost;
                // 持久化存储
                savePostsToStorage(state.posts);
            }
        },
        // 关注
        follow: (state, action) => {
            const { postid, focus,userId,fans } = action.payload;
            // 被关注的项
            const postIndex = state.posts.findIndex((p) => p.id === postid);
            // 关注别人的项
            const fpostIndex = state.posts.findIndex((p)=>p.userId === userId)
            // const post = state.posts.find((p) =>p.id === postId );
            if (postIndex !== -1) {
                const post = state.posts[postIndex]
                const fpost = state.posts[fpostIndex]

                const newFans = [fans,...post.fans]
                const updatedPost = {
                    ...post,
                    fans: newFans
                };
                state.posts[postIndex] = updatedPost

                const newFocus = [focus,...fpost.focus]
                const fupdatePost = {
                    ...fpost,
                    focus:newFocus
                }
                state.posts[fpostIndex] = fupdatePost
                savePostsToStorage(state.posts);
            }
        },
        // 怎么清除我新添加的帖子，已经使用reduxjs/toolkit存储过的新帖子
        // 清除所有帖子
        clearPosts: (state) => {
            state.posts = []; // 清空帖子数组
            savePostsToStorage([]); // 清空本地存储
        },
        resetPosts: (state) => {
            state.posts = posts
            savePostsToStorage(posts)

        },
    },
});
// 存储帖子数据到 AsyncStorage
const savePostsToStorage = async (posts) => {
    try {
        await AsyncStorage.setItem('@posts', JSON.stringify(posts));
    } catch (e) {
        console.error('保存数据失败', e);
    }
};

// 加载帖子数据
const loadPostsFromStorage = async (dispatch) => {
    try {
        const postsData = await AsyncStorage.getItem('@posts');
        if (postsData !== null) {
            dispatch(setPosts(JSON.parse(postsData)));
        }
    } catch (e) {
        console.error('加载数据失败', e);
    }
};

export const { 
    setPosts, 
    addPost, 
    addComment, 
    addGood, 
    follow, 
    clearPosts,
    resetPosts 
} = postSlice.actions;
export default postSlice.reducer;
export const loadPosts = () => async (dispatch) => {
    await loadPostsFromStorage(dispatch);
};
